/* PaddingUtilities.java
 * Author: liuex
 * 2007-12-17 ����08:48:04
 *
 * Note: 
 */
package org.lex.utils.text;

public class PadUtilities {
	private static final char[] SPACES;
	static {
		SPACES = new char[80];
		for (int i = 0; i < SPACES.length; i++)
			SPACES[i] = ' ';
	}

	private PadUtilities() {
	}

	public static String pad(String src, int min, int max) {
		return pad(src, new StringBuilder(), true, min, max).toString();
	}

	public static String pad(String src, boolean leftToRight, int min, int max) {
		return pad(src, new StringBuilder(), leftToRight, min, max).toString();
	}

	/**
	 * @param src
	 * @param dest
	 * @param leftToRight
	 * @param min
	 * @param max
	 * @return
	 */
	public static StringBuilder pad(String src, StringBuilder dest, boolean leftToRight, int min, int max) {
		if (true == leftToRight)
			return padLeftToRight(src, dest, min, max);
		else
			return padRightToLeft(src, dest, min, max);
	}

	// we assume that min <= max
	private static StringBuilder padLeftToRight(String src, StringBuilder dest, int min, int max) {
		int length = src.length();
		if (length >= max) {
			// src is too long, we need to cut the right-part
			return dest.append(src.substring(0, max));
		} else if (length < min) {
			// src is too short, we need to fill some spaces at right-part
			dest.append(src);
			return padSpaces(dest, min - length);
		} else {
			// now we got: min <= length < max
			return dest.append(src);
		}
	}

	private static StringBuilder padRightToLeft(String src, StringBuilder dest, int min, int max) {
		int length = src.length();
		if (length >= max) {
			return dest.append(src.substring(length - max));
		} else if (length < min) {
			padSpaces(dest, min - length);
			return dest.append(src);
		} else {
			return dest.append(src);
		}
	}

	private static StringBuilder padSpaces(StringBuilder dest, int length) {
		while (true) {
			if (length <= SPACES.length)
				return dest.append(SPACES, 0, length);
			else {
				dest.append(SPACES);
				length -= SPACES.length;
			}
		}
	}
}
